package wsi.depend.assist;

import java.io.File;
import java.util.List;

import org.rygh.core.util.UIo;
import org.rygh.core.xml.XmlPath;
import org.rygh.semantic.gui.swing.input.Input;

import wsi.dataguide.tree.WSXmlLeaf;
import wsi.dataguide.tree.WSXmlParser;
import wsi.dataguide.tree.WSXmlTree;
import wsi.depend.model.Dependency;
import wsi.detect.Caller;
import wsi.function.DirManager;
import wsi.function.Function;
import wsi.match.SubtreeController;

public class Assistant extends Dependency {

	private SubtreeController subtreeController;

	public Assistant(Function dependant, Function provider) {
		super(dependant, provider);
	}

	public void assist() {
		System.out.printf("assisted by %s\n", getAssistant().getName());

		DirManager dir = subtreeController.getDirManager();
		File append_dir = dir.getXmlAppendDir();

		if (!append_dir.exists())
			append_dir.mkdir();

		DirManager dir_a = new DirManager(getAssistant());
		Caller caller_a = new Caller(dir_a);

		Input[] inputs = subtreeController.getDirManager().getInputs();

		int a = 1, b = 1;
		assert b > -1;

		for (Input i : inputs) {
			List<WSXmlLeaf> subroots = subtreeController.getSubroots(i);
			WSXmlTree xmltree = subtreeController.getXmlTree(i);

			System.out.printf("input %d / %d, %d subtrees: %s\n", a++,
					inputs.length, subroots.size(), i.getValue());
			b = 1;

			for (WSXmlLeaf r : subroots) {
				// System.out.printf("subtree %d / %d\n", b++, subroots.size());

				XmlPath path = new XmlPath(String.format("%s/%s", r.getXpath(),
						xpath));
				WSXmlLeaf node = r.getNodeByXPath(path);

				if (node == null)
					continue;

				String val = node.getValue().getValue();
				// System.out.printf("depend value %s\n", val);

				Input inp = new Input(val);
				String html = caller_a.call(inp);

				if (html == null)
					continue;

				WSXmlParser parser = new WSXmlParser(inp, html, true);
				WSXmlTree tree = parser.parse();

				if (!parser.isValid())
					continue;

				/*
				 * append prefixes, append tree with new root name
				 * (appended_tree)
				 */

				xmltree.mergePrefix(tree);
				WSXmlLeaf child = tree.getConcreteRoot();
				child.setName("appended_tree");

				r.addChild(child);
			}

			File file = Caller.getXmlFile(i, append_dir);
			UIo.saveFile(file, xmltree.toXmlString());
		}

	}

	/**
	 * getArtistById depends on getArtistByName. but getArtistByName needs
	 * getArtistById to assist. Thus, assistant = dependant.
	 * 
	 * @return
	 */
	public Function getAssistant() {
		return getDependant();
	}

	public void setSubtreeController(SubtreeController subtreeController) {
		this.subtreeController = subtreeController;
	}

}
